package org.jeecg.common.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author lixin
 * @className FilePathUtil
 * @description
 * @date 2020/6/9 15:18
 */
@Slf4j
public class FilePathUtil {

    @Value("${app.upload-dir}")
    private String uploadDir;

    public static String convertTemplatePath(String path) {
        // 如果是windows 则直接返回
        if (System.getProperties().getProperty("os.name").contains("Windows")) {
            return path;
        }

        Resource resource = new ClassPathResource(path);
        FileOutputStream fileOutputStream = null;
        // 将模版文件写入到 tomcat临时目录
        String folder = System.getProperty("excel");
        if(folder == null){
            folder = "excel";
        }
        File tempFile = new File(folder + File.separator + path);
        // System.out.println("文件路径：" + tempFile.getPath());

        File parentFile = tempFile.getParentFile();
        // 判断父文件夹是否存在
        if (!parentFile.exists()) {
            parentFile.mkdirs();
        }
        try {
            BufferedInputStream bufferedInputStream = new BufferedInputStream(resource.getInputStream());
            fileOutputStream = new FileOutputStream(tempFile);
            byte[] buffer = new byte[10240];
            int len = 0;
            while ((len = bufferedInputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return tempFile.getPath();
    }

    /**
     * 删除服务器文件
     * @param filePath 文件的完整路径（从存储根目录开始的相对路径）
     */
    public  boolean deleteFile(String filePath) {
        if (StringUtils.isBlank(filePath)) return false;

        try {
            Path fullPath = Paths.get("./uploads", filePath).normalize();

            // 防止路径穿越攻击
            if (!fullPath.startsWith("uploads")) {
                log.error("非法文件路径: {}", filePath);
                return false;
            }

            return Files.deleteIfExists(fullPath);
        } catch (InvalidPathException e) {
            log.error("路径解析失败: {}", filePath);
            return false;
        } catch (IOException e) {
            log.error("文件删除异常: {}", e.getMessage());
            return false;
        }
    }
}
